const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const minus = document.querySelector(".minus");
const add = document.querySelector(".add");
const show = document.querySelector(".show");
const close = document.querySelector(".close");
const colorPicker = document.getElementById("colorPicker");
let fontSize = 10;
let isDrawing = false; // 标志是否正在绘制
// 获取鼠标在 canvas 上的相对位置
function getMousePos(event) {
  const rect = canvas.getBoundingClientRect();
  return {
    x: event.clientX - rect.left,
    y: event.clientY - rect.top,
  };
}
// 设置 canvas 的绘图区域与父容器等宽
function resizeCanvas() {
  canvas.width = canvas.offsetWidth; // 设置实际绘图宽度为当前展示的宽度
  canvas.height = canvas.offsetHeight; // 可以根据需要调整高度
}
resizeCanvas();

// 鼠标按下，开始绘制
canvas.addEventListener("mousedown", (event) => {
  isDrawing = true;
  const pos = getMousePos(event);
  console.log(pos);
  // 开始新的路径
  ctx.beginPath();
  ctx.moveTo(pos.x, pos.y); // 把路径起点移动到鼠标的初始位置
  ctx.lineWidth = fontSize;
  ctx.strokeStyle = colorPicker.value;
});

// 鼠标移动，绘制路径
canvas.addEventListener("mousemove", (event) => {
  if (isDrawing) {
    const pos = getMousePos(event);
    console.log(pos);
    // 跟踪鼠标移动，绘制路径
    ctx.lineTo(pos.x, pos.y);
    ctx.stroke(); // 进行描边
  }
});

// 鼠标抬起，停止绘制
canvas.addEventListener("mouseup", () => {
  isDrawing = false;
});

// 鼠标离开 canvas，停止绘制
canvas.addEventListener("mouseleave", () => {
  isDrawing = false;
});

close.addEventListener("click", () => {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除整个画布
});

add.addEventListener("click", () => {
  fontSize += 5;
  show.textContent = fontSize;
});

minus.addEventListener("click", () => {
  fontSize -= 5;
  show.textContent = fontSize;
});
